# Skripta ki skrbi za povezavo s ASYS
import sys
import System
import System.Threading
import clr
import time
import threading
import thread
import ee3
import ee3_gui

clr.AddReference('System')
clr.AddReference('System.Windows.Forms')
from System.ComponentModel import BackgroundWorker
clr.AddReference("SAP_SnPn")
from SAP_SnPn import *
from System.Collections import *
from System.Threading import *


#
# POVEZAVA Z SAP
#
#
# POVEZAVA Z SAP
#
def _poizvedbaSAPnalog(izdelek):
        ee3_gui.barva_obrazca('Blue')
        try:
            sappoizvedba = SAP_400()
            ee3_gui.barva_obrazca('None')
            return sappoizvedba.getOrder(izdelek)
        except Exception as e:
            ee3.debug.TraceDbg("Poizvedba na SAP neuspesna!", e.message.ToString(), "Warning")
        ee3_gui.barva_obrazca('None')

def bg_poizvedbaSAPnalog(sender, args):
    tmp = _poizvedbaSAPnalog(args.Argument[0])
    args.Result = tmp


def bg_poizvedbaSAPnalog_completed(sender, args):
    tmp = args.Result
    if (tmp != None):
        ee3.obrazec.comboBox_izdelki.SelectedItem = tmp[1]
        ee3.obrazec.comboBox_delnalogi.SelectedItem = tmp[0].lstrip("0")


def poizvedbaSAPnalog(izdelek):
    worker = BackgroundWorker()
    worker.DoWork += bg_poizvedbaSAPnalog
    worker.RunWorkerCompleted += bg_poizvedbaSAPnalog_completed
    worker.RunWorkerAsync([izdelek])




def _poizvedbaSAPprocesneserijske(nalog):
        try:
            sappoizvedba = SAP_400()
            return sappoizvedba.getData(nalog)
        except Exception as e:
            ee3.debug.TraceDbg("Poizvedba na SAP neuspesna!", e.message.ToString(), "Warning")
            return e.message.ToString()

def bg_poizvedbaSAPprocesneserijske(sender, args):
    tmp = _poizvedbaSAPprocesneserijske(args.Argument[1])
    args.Result = [tmp, args.Argument[0], args.Argument[1]]
    
def bg_poizvedbaSAPprocesneserijske_completed(sender, args):
    if (args.Result[0] != None):
        if (type(args.Result[0]) != str):
            print("Rezultati iz SAPa za nalog %s (%s kosov)" %(args.Result[2], args.Result[0][0].Count))
            for i in range(args.Result[0][0].Count):
                print("%s - %s" %(args.Result[0][0][i], args.Result[0][1][i]))
    ee3.ProcesneSerijske_SAP = args.Result[0]


def poizvedbaSAPprocesneserijske(lista, nalog):
    worker = BackgroundWorker()
    worker.DoWork += bg_poizvedbaSAPprocesneserijske
    worker.RunWorkerCompleted += bg_poizvedbaSAPprocesneserijske_completed
    worker.RunWorkerAsync([lista, nalog])

